import {Topic} from 'knex/types/tables'
import {redisSQLDatabase} from 'TYPE'
import {cache} from '../cache'
import knex from '../sql'

declare module 'knex/types/tables' {
    interface Topic {
        id: number
        name: string
        sid: number // subarea id
        thumbnail: string
    }
    interface Tables {
        topics: Topic
    }
}

class TopicDB implements redisSQLDatabase {
    async getTopicById(id: number) {
        let key = `topic:${id}`
        let topic: Topic = await cache.json.get(key) as any
        return topic
    }
    async loadTopicById(id: number) {
        let key = `topic:${id}`
        let topic: Topic = null
        await knex('topics').select().where({id}).first().then(t => {
            if (t) {
                topic = t
                cache.json.set(key, '$', topic as any)
            }
        })
        return topic
    }
    async loadAll() {
        await cache.keys('topic:*').then(async (keys) => {
            for (const key of keys) {
                await cache.del(key)
            }
        })
        await knex('topics').select().then(ts => {
            for (let topic of ts) {
                let key = `topic:${topic.id}`;
                (topic as any).comment_num = 0
                cache.json.set(key, '$', topic as any)
            }
        })
    }

}
export const topicDB = new TopicDB()
